package com.gwtgeo.ui.client.mvp.searchresults;

import java.util.List;
import java.util.Map;

import net.customware.gwt.presenter.client.EventBus;

import com.google.inject.Inject;
import com.gwtgeo.service.model.Location;
import com.gwtgeo.ui.client.mvp.HasValues;
import com.gwtgeo.ui.client.mvp.Saveable;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowTypeEnum;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowedDisplay;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowedPresenter;
import com.gwtgeo.ui.shared.event.SearchFinishedEvent;
import com.gwtgeo.ui.shared.event.SearchFinishedEventHandler;
import com.gwtgeo.ui.shared.event.SelectionRetrievedEvent;
import com.gwtgeo.ui.shared.event.SelectionRetrievedEventHandler;

public class SearchResultsPresenter extends
		WindowedPresenter<SearchResultsPresenter.Display> implements Saveable<List<Location>, List<Location>>{

	public interface Display extends WindowedDisplay {

		HasValues<Location> getResults();

	}

	@Inject
	public SearchResultsPresenter(Display display, EventBus eventBus) {
		super(display, eventBus);
	}

	@Override
	public void init(Map<String, Object> params) {
		display.getResults().clear();
	}

	@Override
	public WindowTypeEnum getType() {
		return WindowTypeEnum.SEARCH_RESULTS;
	}

	@Override
	protected void onBind() {
		super.onBind();
		this.registerHandler(this.eventBus.addHandler(SearchFinishedEvent.TYPE,
				new SearchFinishedEventHandler() {

					@Override
					public void onSearchFinished(SearchFinishedEvent event) {
						display.getResults().setValues(event.getLocations());
					}
				}));

		this.registerHandler(this.eventBus.addHandler(
				SelectionRetrievedEvent.TYPE,
				new SelectionRetrievedEventHandler() {

					@Override
					public void onSelectionRetrieved(
							SelectionRetrievedEvent event) {
						display.getResults().selectValues(event.getLocations());
					}
				}));
	}

	@Override
	public List<Location> buildSaveableModel() {
		return display.getResults().getValues();
	}

	@Override
	public List<Location> load(List<Location> def) {
		display.getResults().setValues(def);
		return def;
	}

	@Override
	protected void onRevealDisplay() {

	}

	@Override
	protected void onUnbind() {

	}
}
